package com.auoem.radio.common.custview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;

import com.auctus.am.framework.utils.LogM;
import com.auoem.radio.common.filter.EnglishCharFilter;
import com.auoem.radio.common.imp.KeyboardManager;
import com.auoem.radio.common.utils.ResourceUtils;
import com.auoem.radio.common.utils.ScreenUtils;
import com.auoem.radio.databinding.FragmentEditDialogBinding;

public class EditDialogFragment extends DialogFragment {

    private final static int MAX_LEN = 200;

    private FragmentEditDialogBinding mBinding;
    private OnEditFinishListener mOnEditFinishListener;

    private String mDefaultValue = "";
    private String mTitle = "";
    private int mMaxLength = 20;
    private int mInputType = InputType.TYPE_CLASS_TEXT;

    private String digist;

    public EditDialogFragment() {
    }

    public EditDialogFragment(@NonNull String title, String defaultValue) {
        mTitle = title;
        mDefaultValue = defaultValue == null ? "" : defaultValue;
    }

    public EditDialogFragment(@NonNull int title, int defaultValue) {
        if (title != 0) {
            mTitle = ResourceUtils.getResourcesString(title);
        }
        if (title != 0) {
            mDefaultValue = ResourceUtils.getResourcesString(defaultValue);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = FragmentEditDialogBinding.inflate(inflater, container, false);
        initView();
        return mBinding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    private void updateAttr() {
        if (mMaxLength > 0 && mMaxLength < 200) {
//            mBinding.contentEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});
            setFilter();
        }

        if (!TextUtils.isEmpty(digist)) {
            mBinding.contentEt.setKeyListener(DigitsKeyListener.getInstance(digist));
        }
    }

    public void setAttr(int maxLen, String digist) {
//        if (maxLen > 0 && maxLen < 200) {
//            mMaxLength = maxLen;
//        }
        setMaxLength(maxLen);

        if (!TextUtils.isEmpty(digist)) {
            this.digist = digist;
//            mBinding.contentEt.setKeyListener(DigitsKeyListener.getInstance(digist));
        }
    }

    public void setInputType(int inputType) {
        mBinding.contentEt.setInputType(inputType);
    }

    public void setContent(@NonNull String title, String defaultValue) {
        mTitle = title;
        mDefaultValue = TextUtils.isEmpty(defaultValue) ? "" : defaultValue;
//        mBinding.titleTv.setVisibility(TextUtils.isEmpty(title) ? View.INVISIBLE : View.VISIBLE);
        mBinding.titleTv.setText(mTitle);
        mBinding.contentEt.setText(mDefaultValue);
        LogM.d("setContent: " + mDefaultValue);
    }

    private void initView() {
        mBinding.titleTv.setText(mTitle);
        mBinding.contentEt.setInputType(mInputType);
        mBinding.contentEt.setHorizontallyScrolling(false);
        mBinding.contentEt.setText(mDefaultValue);
        mBinding.cancelButton.setOnClickListener(v -> {
            dismiss();
        });
        mBinding.okButton.setOnClickListener(v -> {
            if (mOnEditFinishListener != null) {
                mOnEditFinishListener.onFinished(mBinding.contentEt.getText().toString());
            }
            dismiss();
        });
//        mBinding.contentEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});
        setFilter();
        mBinding.contentEt.setSelection(mDefaultValue == null ? 0 : mDefaultValue.length());
        updateAttr();
    }

    private void setFilter() {
//        mBinding.contentEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});//原
        EnglishCharFilter inputFilterMaxLen = new EnglishCharFilter(mMaxLength);
        mBinding.contentEt.setFilters(new InputFilter[]{inputFilterMaxLen});
    }

    public void setEditInputType(int type) {
        LogM.d("AAA", "setEditInputType: 1111");
        mInputType = type;
    }

    public void setMaxLength(int maxLength) {
//        mMaxLength = maxLength;
        mMaxLength = Math.max(maxLength, 0);
        mMaxLength = Math.min(mMaxLength, MAX_LEN);
    }

    public void setLines(int lines) {
//        mMaxLength = maxLength;
        mBinding.contentEt.setLines(lines);
        if (lines > 1) {
            mBinding.contentEt.setHeight(ScreenUtils.dip2px(30 * lines + 10));
        } else {
//            mBinding.contentEt.setHeight(ScreenUtils.dip2px(20 ));
        }
        LogM.d(this.getClass().getName(), "setLines: " + lines);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            //TODO:连续点击某处会使getActivity()为空导致应用崩溃
            //Hack:1 trycatch, 2 if null
            FragmentActivity fActivity = getActivity();
            if (fActivity == null)
                return;
            mBinding.contentEt.requestFocus();
            KeyboardManager.showInputKeyboard(getActivity().getApplicationContext(), mBinding.contentEt);
        }, 300);
    }

    public void setOnEditFinishListener(OnEditFinishListener onEditFinishListener) {
        mOnEditFinishListener = onEditFinishListener;
    }

    public interface OnEditFinishListener {
        void onFinished(String content);
    }

}
